package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;
/**
 * 缓存数据初始化监听器
 */
//ContextRefreshedEvent:上下文更新事件
//@Component//声明配置类
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyStatisVORedisService statisVORedisService;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("---------------攻略vo对象初始化start-----------");
        //获取所有攻略
        List<Strategy> list = strategyService.list();
        //遍历攻略,封装成vo对象
        for (Strategy strategy : list) {
           /* 存在问题:如果第一次初始化后,前端进行vo对象统计,redis中统计数据跟数据库中数据不一致
                    如果第二次再进行初始化,后面操作会覆盖之前redis缓存的vo对象
            解决方案:如果vo已经存在,直接跳过,不需要初始化     */
            //判断攻略是否存在,存在跳过
            if (statisVORedisService.isStrategyExist(strategy.getId())) {
                continue;
            }
            //不存在,创建vo
            StrategyStatisVO vo = new StrategyStatisVO();
            //把攻略数据复制到vo对象
            BeanUtils.copyProperties(strategy, vo);
            //补全缺少的StrategyId
            vo.setStrategyId(strategy.getId());
            //把vo对象设置进去
            statisVORedisService.setStrategyStatisVO(vo);
            System.out.println("---------------攻略vo对象初始化end-----------");
        }
    }
}
